package com.google.appengine.a4ieve.filters;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.a4ieve.Helper;
import com.google.appengine.a4ieve.entities.CuratorWrapper;
import com.google.appengine.a4ieve.entities.StudentWrapper;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.UserServiceFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: lunin
 * Date: 4/14/14
 * Time: 11:37 AM
 */
public class StudentFilter implements Filter{

    private static final Pattern EXCLUDE_URLS = Pattern.compile("^.*/(admin|ajax)/.*$", Pattern.CASE_INSENSITIVE);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //nothing here
    }

    private boolean isWorthyRequest(HttpServletRequest request) {
        String url = request.getRequestURI();
        Matcher m = EXCLUDE_URLS.matcher(url);
        return (!m.matches());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //here we have to query the database and get the group name
        if (!isWorthyRequest((HttpServletRequest)servletRequest)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String key = Helper.cropEmailId(UserServiceFactory.getUserService().getCurrentUser().getEmail());
        Query studentQuery = new Query(StudentWrapper.KIND_KEY).addProjection(StudentWrapper.GROUP_KEY_PROJECTION).
                addFilter(
                        StudentWrapper.USER_ID_PROPERTY,
                        Query.FilterOperator.EQUAL,
                        key
                );
        DatastoreService service = DatastoreServiceFactory.getDatastoreService();
        Entity storedEntity = service.prepare(studentQuery).asSingleEntity();
        if (storedEntity == null) {
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not associated with any group. Go away, " +
                    UserServiceFactory.getUserService().getCurrentUser().getEmail());
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            request.getSession().setAttribute(Const.GROUP, storedEntity.getProperty(CuratorWrapper.GROUP_KEY_PROPERTY));
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        //nothing here
    }
}
